import api from '@/api/user'
import { reactive } from 'vue'
import {
  PROBLEM_SUBMIT_TYPE,
  STATUS,
  ITRAIN_OPERATION,
  PASS_OPTION,
  PROBLEM_SUBMIT_STATUS,
  CATEGORY_STATUS,
} from '@/constant'

export const itrainState = reactive({
  showModal: false,
  catId: null,
  catOptions: [],
  msg: '',
  drawProblem: false,
})

export const submitProblem = async ({
  examId,
  submitOnlyAC,
  problemId,
  problemStatus,
  problemSequence = '', // 可不传
  problemTitle,
  problemScore = -1024, // 可不传
  catId = '', // 智能训练提交需要
  continueTrain = '', // 智能训练提交需要
  successCallback = () => {},
  failCallback = () => {},
}) => {
  // 请求提交
  const postThisProblem = async (submitType) => {
    try {
      if (catId) {
        const res = await api.submitItrainThisProblem({
          problemId,
          examId,
          submitType,
          catId,
          continueTrain,
        })
        successCallback(res.data)
        if (res.data === PROBLEM_SUBMIT_STATUS.SUBMIT_FINISHED) {
          $dialog.success({
            title: '提示',
            content: '已经通关，提交本题后不影响已获得分数！',
            positiveText: '确定',
            onPositiveClick: () => {
              getNextResult(examId, catId, continueTrain)
            },
          })
        } else {
          getNextResult(examId, catId, continueTrain)
        }
      } else {
        const res = await api.submitThisProblem({
          problemId,
          examId,
          submitType,
        })
        successCallback(res.data)
      }
    } catch (err) {
      if (err.code === 40001) {
        $dialog.error({
          title: '题目涉嫌抄袭',
          content: () => {
            return h('div', { style: 'color:#d13050' }, [
              h('p', `题目名：${problemTitle} 涉嫌抄袭！`),
              h('p', '你确认要提交本题吗？'),
            ])
          },
          negativeText: '坚持提交',
          positiveText: '取消提交',
          onNegativeClick: () => {
            // console.log('COPY - 确认提交')
            postThisProblem(PROBLEM_SUBMIT_TYPE.COPIED)
          },
        })
      } else {
        console.error(err)
      }
      failCallback(err)
    }
  }

  // 不能够提交本题的情况分2种情况
  // 1.submitOnlyAC为true，并且题目状态不为AC
  // 2.submitOnlyAC为false，并且题目状态为QUEUE|WAIT|REDO|空
  if (
    (submitOnlyAC === true && problemStatus != STATUS.AC) ||
    (submitOnlyAC != true &&
      (problemStatus === STATUS.QUEUE ||
        problemStatus === STATUS.WAIT ||
        problemStatus === STATUS.REDO ||
        problemStatus === ''))
  ) {
    // 如果状态为空，另外提示
    if (problemStatus == '') {
      $message.error('本题现在状态为空，暂时不能提交本题。')
    } else {
      // 提示本场考试当前状态不能提交本题
      $message.error(`当前题目状态为${problemStatus}，不能提交本题。`)
    }
  } else {
    //1.已经AC提交；2.未AC提交；
    switch (problemStatus) {
      case STATUS.AC:
        $dialog.info({
          title: '提示',
          content: () => {
            return h('div', [
              h(
                'p',
                {},
                problemSequence
                  ? `“${problemSequence}. ${problemTitle}” 已 AC 但未提交`
                  : `本题 “${problemTitle}” 已 AC 但未提交`
              ),
              h(
                'p',
                {},
                '提交本题后才能将本题得分计入成绩，但可以继续提交代码，提交本题后提交代码不影响计分'
              ),
              h('p', {}, '你确认要提交本题吗？'),
            ])
          },
          negativeText: '取消',
          positiveText: '提交',
          onPositiveClick: () => {
            // console.log('AC - 确认提交')
            postThisProblem(PROBLEM_SUBMIT_TYPE.NORMAL)
          },
        })
        break

      default:
        $dialog.confirm({
          title: '是否提交本题',
          type: 'info',
          content: () => {
            return h('div', [
              h('p', {}, ['您当前本题的得分为：', h('span', {}, problemScore)]),
              h(
                'p',
                {},
                '提交本题后才能将本题得分计入成绩，但可以继续提交代码，提交本题后提交代码不影响计分'
              ),
              h('p', {}, '你确认要提交本题吗？'),
            ])
          },
          confirm() {
            // console.log('没有AC - 确认提交')
            postThisProblem(PROBLEM_SUBMIT_TYPE.NORMAL)
          },
        })
    }
  }
}

export const drawProblem = async (examId, catId, router) => {
  if (!catId) {
    $message.error('请选择一个类别')
    return
  }
  try {
    const res = await api.getItrainProbCatgory({
      examId: examId,
      catId: catId,
    })
    const { status, openingTime } = res.data
    if (status === CATEGORY_STATUS.SCHEDULE_OPEN && openingTime > Date.now()) {
      $message.info('本关还未开放，请切换到其它类别')
      return
    }
  } catch (error) {
    console.log(error)
  }
  try {
    const res = await api.drawProblem({
      examId: examId,
      secCatgory_id: catId,
    })

    var proId = res.data.problemId
    if (proId !== 0) {
      router.replace({
        path: `/user/training/${examId}/problems/${proId}`,
        query: { catId: catId, continueTrain: 'yes' },
      })
      itrainState.showModal = false
    } else {
      $message.info('本关所有题目已完成，请选择其它类别!')
    }
  } catch (error) {
    console.log(error)
  }
}

const initItrainState = () => {
  itrainState.showModal = false
  itrainState.catId = null
  itrainState.catOptions.length = 0
  itrainState.msg = ''
  itrainState.drawProblem = false
}

const getNextResult = async (examId, secCatgory_id, continueTrain) => {
  try {
    const res = await api.getSubmitProblemResult({
      examId,
      secCatgory_id,
    })
    const { category, operation, passOption } = res.data
    initItrainState()
    if (continueTrain === 'no' && operation === ITRAIN_OPERATION.PASS) {
      $dialog.info({
        title: '提示',
        content: '恭喜您，已通关！',
        positiveText: '确定',
      })
    } else if (continueTrain === 'yes') {
      itrainState.showModal = true
      if (operation === ITRAIN_OPERATION.PASS) {
        console.log(passOption)
        console.log(itrainState)
        if (passOption === PASS_OPTION.FINISHED) {
          itrainState.msg = '恭喜您，已通关！'
          var localOptions = category.map((item) => ({
            label: `(${item.rowX}.${item.colY}) ${item.name1}->${item.name2}`,
            value: item.catId,
          }))
          itrainState.catOptions.length = 0
          itrainState.catOptions.push(...localOptions)
        } else {
          itrainState.msg = '您已通关，可以选择继续做本关的题目'
          itrainState.catId = secCatgory_id
        }
        itrainState.drawProblem = true
      } else if (operation === ITRAIN_OPERATION.EXCEED_DEADLINE) {
        itrainState.msg = '本关截止时间已过,请点“我要通关”结束本关'
      } else if (operation === ITRAIN_OPERATION.ALL_PROBLEMS_FINISHED) {
        itrainState.msg = '本关所有题目已完成，请点“我要通关”结束本关'
      } else if (operation === ITRAIN_OPERATION.NEXT_PROBLEM) {
        itrainState.catId = secCatgory_id
        itrainState.msg = '即将开始下一题，请预留足够时间，确认？'
        itrainState.drawProblem = true
      } else {
        console.error(`未知的操作：${operation}`)
      }
    }
  } catch (err) {
    console.error(err)
  }
}
